package com.feng.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feng.chat.common.Common;
import com.feng.chat.dto.AnnexRecoverListDTO;
import com.feng.chat.dto.AnnexUploadDTO;
import com.feng.chat.dto.Result;
import com.feng.chat.entity.Article;
import com.feng.chat.entity.ArticleAnnex;
import com.feng.chat.mapper.ArticleAnnexMapper;
import com.feng.chat.mapper.ArticleMapper;
import com.feng.chat.service.IArticleAnnexService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.chat.vo.AnnexUploadVO;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 笔记附件信息表 服务实现类
 * </p>
 *
 * @author dyf
 * @since 2022-05-31
 */
@Service
public class ArticleAnnexServiceImpl extends ServiceImpl<ArticleAnnexMapper, ArticleAnnex> implements IArticleAnnexService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleAnnexMapper articleAnnexMapper;

    /**
     * 上传笔记附件
     *
     * @param uid
     * @param annexUploadVO
     * @return
     */
    @Override
    public Result annexUpload(Integer uid, AnnexUploadVO annexUploadVO) {
        Article article = articleMapper.selectById(annexUploadVO.getArticle_id());
        if (article.getStatus() == 1) {
            MultipartFile annex = annexUploadVO.getAnnex();

            String path = "E:\\Desktop\\案例\\javaweb案例\\MyChat\\resource\\articleAnnex\\";
            String oldFileName = annex.getOriginalFilename();
            String suffix = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);
            long size = annex.getSize();
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "");
            path = path + newFileName;
            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            try {
                annex.transferTo(file);
            } catch (IOException e) {
                return Result.fail();
            }

            ArticleAnnex articleAnnex = new ArticleAnnex();
            articleAnnex.setArticleId(article.getId());
            articleAnnex.setOriginalName(oldFileName);
            articleAnnex.setPath(path);
            articleAnnex.setSize(size);
            articleAnnex.setSuffix(suffix);
            articleAnnex.setUserId(uid);

            articleAnnexMapper.insert(articleAnnex);

            AnnexUploadDTO annexUploadDTO = new AnnexUploadDTO();
            annexUploadDTO.setId(articleAnnex.getId());
            annexUploadDTO.setOriginal_name(articleAnnex.getOriginalName());
            annexUploadDTO.setPath(articleAnnex.getPath());
            annexUploadDTO.setSize(articleAnnex.getSize());
            annexUploadDTO.setSuffix(articleAnnex.getSuffix());
            return Result.success(annexUploadDTO);
        }
        return Result.fail("该笔记不存在或已删除！");
    }

    /**
     * 附件下载
     *
     * @param response
     * @param annex_id
     * @return
     */
    @Override
    public void annexDownload(HttpServletResponse response, Integer annex_id) throws Exception {
        ArticleAnnex articleAnnex = articleAnnexMapper.selectById(annex_id);
        File file = new File(articleAnnex.getPath());
        InputStream inputStream = new FileInputStream(file);

        response.reset();
        response.setContentType("application/octet-stream");
        String filename = articleAnnex.getOriginalName();
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }

    /**
     * 删除附件
     *
     * @param annex_id
     * @return
     */
    @Override
    public Result annexDelete(Integer annex_id) {
        ArticleAnnex articleAnnex = articleAnnexMapper.selectById(annex_id);
        articleAnnex.setStatus(2);
        articleAnnex.setDeletedAt(LocalDateTime.now());

        articleAnnexMapper.updateById(articleAnnex);
        return Result.success();
    }

    /**
     * 笔记附件回收站列表
     *
     * @param uid
     * @return
     */
    @Override
    public Result recoverList(Integer uid) {
        QueryWrapper<ArticleAnnex> articleAnnexQueryWrapper = new QueryWrapper<>();
        articleAnnexQueryWrapper.eq("user_id", uid).eq("status", 2);
        List<ArticleAnnex> articleAnnexes = articleAnnexMapper.selectList(articleAnnexQueryWrapper);

        List<AnnexRecoverListDTO> annexRecoverListDTOS = new ArrayList<>();
        annexRecoverListDTOS = articleAnnexes.stream().map(item -> {
            AnnexRecoverListDTO annexRecoverListDTO = new AnnexRecoverListDTO();
            annexRecoverListDTO.setArticle_id(item.getArticleId());
            annexRecoverListDTO.setId(item.getId());
            annexRecoverListDTO.setOriginal_name(item.getOriginalName());

            //剩余天数
            Integer day = 30 - (LocalDateTime.now().getDayOfYear() - item.getDeletedAt().getDayOfYear());
            annexRecoverListDTO.setDay(day);

            Article article = articleMapper.selectById(item.getArticleId());
            annexRecoverListDTO.setTitle(article.getTitle());
            return annexRecoverListDTO;
        }).collect(Collectors.toList());
        Map<String, List<AnnexRecoverListDTO>> map = new HashMap<>();
        map.put("rows", annexRecoverListDTOS);
        return Result.success(map);
    }

    /**
     * 恢复笔记附件
     * @param annex_id
     * @return
     */
    @Override
    public Result annexRecover(Integer annex_id) {
        ArticleAnnex articleAnnex = articleAnnexMapper.selectById(annex_id);
        articleAnnex.setStatus(1);
        articleAnnex.setDeletedAt(null);
        articleAnnexMapper.updateById(articleAnnex);
        return Result.success();
    }

    /**
     * 永久刪除笔记附件
     * @param annex_id
     * @return
     */
    @Override
    public Result annexForeverDelete(Integer annex_id) {
        ArticleAnnex articleAnnex = articleAnnexMapper.selectById(annex_id);
        articleAnnex.setStatus(3);
        articleAnnex.setDeletedAt(LocalDateTime.now());
        articleAnnexMapper.updateById(articleAnnex);
        return Result.success();
    }
}

